<?php

namespace PKApp\Model;

use PKApp\Model\Classes\TraitModel;
use PKCommon\Controller\AdminSetController;
use PKFrame\DataHandler\Numbers;

class AdminSetOptions extends AdminSetController
{
    use TraitModel;

    public function Main()
    {
        $this->assign([
            'id' => Numbers::To(request()->get('id'))
        ])->fetch('options_form');
    }

    public function ApiByCreate()
    {
        $post = $this->model();
        unset($post['id']);
        $this->serviceOfOptions()->Add($post);
        $this->inputSuccess();
    }

    public function ApiByChange()
    {
        $post = $this->model();
        Numbers::IsId($post['id']) ?: $this->noticeByJson('Options_IdEmpty');
        $post['parentId'] != $post['id'] ?: $this->noticeByJson('Options_ParentError');
        $this->serviceOfOptions()->UpdateById($post['id'], $post);
        $this->inputSuccess();
    }

    public function ApiByDel()
    {
        $id = request()->post('id');
        Numbers::IsId($id) ?: $this->noticeByJson('Options_IdEmpty');
        $this->serviceOfOptions()->DeleteById($id);
        $this->json('Data_Input_Success');
    }

    protected function model(): array
    {
        $post = $this->checkModel(array('id', 'parentId', 'name', 'image'));
        $this->checkPostFieldIsEmpty('name', 'Options_NameEmpty');
        $post['parentId'] = Numbers::To($post['parentId']);
        return $post;
    }
}